﻿using Qy.Core;
using SqlSugar;
using System;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class LogLoginService : QyRepository<LogLogin>
{
    public LogLoginService(ApplicationContext applicationContext) : base( applicationContext) { }

    /// <summary>
    /// 获取全部列表
    /// </summary>
    public async Task<PagedInfo<ViewLogLogin>> GetSqlListAsync(LogLoginQuery parm)
    {
        DateTime startDate = DateUtility.GetBeginTime(parm.StartDate, -1);
        DateTime endDate = DateUtility.GetBeginTime(parm.EndDate, 1);
        var exp = Expressionable.Create<LogLogin>();
        exp = exp.AndIF(parm.Uid != 0, data => data.UserId == parm.Uid);
        exp = exp.AndIF(parm.StartDate != null && parm.EndDate != null, data => data.Time >= startDate && data.Time <= endDate);
        return await Queryable()
            .LeftJoin<User>((data,  user) => data.UserId == user.Id)
            .LeftJoin<UserDept>((data, user, dept) => user.DeptId == dept.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.NickName), (data, user) => user.NickName.Contains(parm.NickName))
            .OrderBy((data) => data.Id, OrderByType.Desc)
            .Select((data, user,dept) => new ViewLogLogin()
            {
                Id = data.Id,
                NickName = user.NickName,
                UserName = user.UserName,
                UserId = data.UserId,
                Ip = data.Ip,
                Time= data.Time,
                DeptName = dept.Name
            })
            .ToPageAsync(parm);
    }

    public async Task<object> InsertLogLoginAsync(int userId, string ip)
    {
        LogLogin logSql = new()
        {
            UserId = userId,
            Ip = ip,
            Time = DateTime.Now
        };
        return await InsertAsync(logSql);
    }
    public bool Clear()
    {
        return  Context.DbMaintenance.TruncateTable<LogLogin>(); 
    }
}
